package org.alis.ap.rpc.transport.http;

import lombok.extern.slf4j.Slf4j;
import org.alis.ap.rpc.transport.RequestHandler;
import org.alis.ap.rpc.transport.TransportServer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Objects;

/**
 * ApTransportServer desc:
 *
 * @author luochuan
 * @date 2020/10/16 16:45
 */
@Slf4j
public class ApTransportServer implements TransportServer {
    private RequestHandler handler;

    private Server server;

    @Override
    public void start() {
        try {
            server.start();
            server.join();
        }catch (Exception e){
            log.error("服务启动异常,异常堆栈->",e);
        }
    }

    @Override
    public void init(int port, RequestHandler requestHandler) {
        this.handler = requestHandler;
        this.server = new Server(port);
        // 这里使用的是servlet来接受的
        ServletContextHandler contextHandler =new ServletContextHandler();
        server.setHandler(contextHandler);

        ServletHolder holder = new ServletHolder(new RequestServlet());
        contextHandler.addServlet(holder,"/*");

    }

    @Override
    public void stop() {
        try {
            server.stop();
        } catch (Exception e) {
            log.error("服务启动失败,异常堆栈->",e);
        }
    }

    class RequestServlet extends HttpServlet {

        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
            log.info("client exec connect");
            InputStream inputStream = req.getInputStream();
            OutputStream outputStream = resp.getOutputStream();
            if(Objects.nonNull(handler)){
                handler.onRequest(inputStream,outputStream);
            }
            outputStream.flush();

        }
    }
}
